package service;

import service.impl.ClickFavoriteServiceImpl;
import util.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class ClickFavoriteService implements ClickFavoriteServiceImpl {
    private final String tableName = " click_favorite ";
    private final String articleField = " article_id ";
    private final String authorField = " author_id ";

    @Override
    public boolean queryiSClick(Integer articleId, Integer authorId) {
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            connection = JDBCUtils.getConnection();
            String sql = "SELECT * FROM " + tableName+ " WHERE "+  articleField + " = ?  AND " +  authorField + " = ?";
            pstmt = connection.prepareStatement(sql);
            pstmt.setInt(1, articleId);
            pstmt.setInt(2, authorId);

            // 执行SQL语句
            rs = pstmt.executeQuery();
            if(!rs.next()){
                //没点过赞
                return false;
            }
            return true;
        } catch (Exception e) {
            System.out.println("点赞查询异常: " + e.getMessage());
            return true;
        }finally {
            JDBCUtils.closeResource(connection,pstmt,rs);
        }
    }

    @Override
    public boolean addNumber(Integer articleId, Integer authorId) {
        //进行插入操作，可能会导致插入失败
        Connection connection = null;
        PreparedStatement pstmt = null;
        try {
            connection = JDBCUtils.getConnection();
            //Statement statement = connection.createStatement();
            String sql = "INSERT INTO " + tableName + "("+ articleField + "," + authorField+   ") VALUES (?,?)";
            pstmt = connection.prepareStatement(sql);
            pstmt.setInt(1, articleId);
            pstmt.setInt(2, authorId);

            // 执行SQL语句
            pstmt.executeUpdate();
            return true;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return false;
        }finally {
            JDBCUtils.closeResource(connection,pstmt);
        }
    }
}
